﻿using System;
using System.Collections.Generic;
using System.Text;
using ttbit.math;
using Rect = System.Drawing.Rectangle;
using RectF = System.Drawing.RectangleF;
namespace ttbit.core
{
    public class Packer_shelf : IPacker
    {
        int texwidth;
        int texheight;
        public Packer_shelf(int texwidth, int texheight)
        {
            this.texwidth = texwidth;
            this.texheight = texheight;
            xpos = 0;
            ypos = 0;
            lineheight = 0;
        }
        public int supportSpriteMaxWidth => 256;

        public int supportSpriteMinWidth => 4;

        public int supportSpriteMaxHeight => 256;

        public int supportSpriteMinHeight => 4;

        int xpos;
        int ypos;
        int lineheight;
        public bool GetFree(ushort width, ushort height, out Rect rect)
        {
            if (width > texwidth || height > texheight) //超宽的不用看
            {
                rect = default(Rect);
                return false;
            }

            int testx = xpos;
            int testy = ypos;
            //不够放，起一行
            if (width > texwidth - testx)
            {
                testy += lineheight;
                testx = 0;
            }
            //行高也不够了
            if (height > texheight - testy)
            {
                rect = default(Rect);
                return false;
            }

            rect = new Rect(testx, testy, width, height);
            xpos = rect.Right;
            ypos = testy;
            lineheight = Math.Max(height, lineheight);
            return true;
        }

        public Rect[] GetFrees(Size[] size)
        {
            Rect[] result = new Rect[size.Length];
            for (var i = 0; i < result.Length; i++)
            {
                if (!GetFree((ushort)size[i].sizeX, (ushort)size[i].sizeY, out result[i]))
                    result[i].Width = result[i].Height = 0;
            }
            return result;
        }
        public float UsedPercent
        {
            get
            {
                return (float)ypos / texheight + ((float)lineheight / texheight) * ((float)xpos / texwidth);
            }
        }
    }
}
